﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.ObjectModel;
using Eassets.Layered.Domain.Global;
using Eassets.Layered.Domain.Secure;
using Eassets.Service.Secure;
using Eassets.Service.Global;

namespace Eassets.UI.Secure
{
    public partial class SecurityScreenForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetAllEassetModules();
                if (treeViewProgramTree.DataSource != null)
                {
                    LoadProgramTree();
                }

            }
        }

        private void GetAllEassetModules()
        {
            EassetModuleService erimsModuleService = new EassetModuleService();

            try
            {
                dropDownListModule.DataSource = erimsModuleService.GetAllEassetModule();
                dropDownListModule.DataValueField = "EassetModuleId";
                dropDownListModule.DataTextField = "Description";
                dropDownListModule.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        protected void dropDownListModule_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void buttonSaveAdd_Click(object sender, EventArgs e)
        {
            if (CheckMandatory("A"))
            {
                try
                {
                    string valuePath = treeViewProgramTree.SelectedNode.ValuePath;

                    Screen screen = new Screen();
                    screen.EassetModuleId = Convert.ToInt64(dropDownListModule.SelectedValue.Trim());
                    screen.Description = textBoxDescriptionAdd.Text.Trim();
                    screen.ParentScreenId = Convert.ToInt64(hiddenFieldScreenId.Value.Trim());
                    screen.ProgramFileName = textBoxProgramFileNameAdd.Text.Trim();
                    screen.Sequence = Convert.ToInt32(textBoxSequenceAdd.Text.Trim());

                    ScreenService screenService = new ScreenService();
                    screenService.AddScreen(screen);

                    FlashMessage1.Display("Successfully Saved", "okmessage");
                    LoadProgramTree();

                    try
                    {
                        String[] strings = valuePath.Split('/');
                        valuePath = "";
                        foreach (string s in strings)
                        {
                            if (valuePath == "")
                            {
                                valuePath = s;
                            }
                            else
                            {
                                valuePath = valuePath + "/" + s;
                            }
                            treeViewProgramTree.FindNode(valuePath).Expand();
                        }
                        //treeViewProgramTree.FindNode(valuePath).ExpandAll();

                    }
                    catch (Exception exception)
                    {
                    }

                    ClearInputs();
                }
                catch (Exception exception)
                {
                    FlashMessage1.Display("Saving Failed", "errormessage");
                }
            }
        }

        private bool CheckMandatory(string saveMode)
        {
            if (saveMode == "A")
            {
                if (hiddenFieldScreenId.Value.Trim() == String.Empty)
                {
                    FlashMessage1.Display("A parent [Menu Option] should be selected to add a sub level", "errormessage");
                    return false;
                }
                else if (textBoxDescriptionAdd.Text.Trim() == String.Empty)
                {
                    FlashMessage1.Display("[Description] cannot be blank", "errormessage");
                    return false;
                }
                else if (textBoxSequenceAdd.Text.Trim() == String.Empty)
                {
                    FlashMessage1.Display("[Sequence] cannot be blank", "errormessage");
                    return false;
                }
            }
            else if (saveMode == ("M"))
            {
                if (hiddenFieldScreenId.Value.Trim() == String.Empty)
                {
                    FlashMessage1.Display("Please select a [Menu Option] to modify", "errormessage");
                    return false;
                }
                else if (textBoxDescriptionModify.Text.Trim() == String.Empty)
                {
                    FlashMessage1.Display("[Description] cannot be blank", "errormessage");
                    return false;
                }
                else if (textBoxSequenceModify.Text.Trim() == String.Empty)
                {
                    FlashMessage1.Display("[Sequence] cannot be blank", "errormessage");
                    return false;
                }
            }
            return true;
        }
        //protected void treeViewProgramTreeNode_Click(object sender, EventArgs e)
        //{

        //}

        private void LoadProgramTree()
        {
            treeViewProgramTree.Nodes.Clear();

            Collection<Screen> Screens = new Collection<Screen>();
            ScreenService erimsScreenService = new ScreenService();
            if (dropDownListModule.SelectedValue != "")
            {
                Screens =
                    erimsScreenService.GetScreenByModuleId(Convert.ToInt64(dropDownListModule.SelectedValue));
            }

            //erimsScreens = new Collection<ErimsScreen>(erimsScreens.OrderBy(x => x.Sequence).ToList());
            TreeNode newNode = new TreeNode("Menu Options", 0.ToString());
            treeViewProgramTree.Nodes.Add(newNode);
            FillTree(Screens, newNode);

            newNode.Expand();
            //treeViewProgramTree.CollapseAll();
        }

        private void FillTree(Collection<Screen> sourceCollection, TreeNode parentTreeNode)
        {
            // Get all children of the current parent
            Collection<Screen> o = new Collection<Screen>(
                sourceCollection.Where(
                    x =>
                    parentTreeNode.Value == 0.ToString()
                        ? x.ParentScreenId == null
                        : (x.ParentScreenId != null) &&
                          (x.ParentScreenId.ToString() == parentTreeNode.Value)).OrderBy(
                    x => x.Sequence).ToList());

            foreach (Screen orig in o)
            {
                TreeNode newNode = new TreeNode(orig.Description, orig.ScreenId.ToString());

                parentTreeNode.ChildNodes.Add(newNode);
                newNode.Collapse();
                FillTree(sourceCollection, newNode);
            }
        }
        protected void treeViewProgramTreeNode_Click(object sender, EventArgs e)
        {
            ScreenService erimsScreenService = new ScreenService();
            Screen screen =
                erimsScreenService.GetByIdScreen(Convert.ToInt64(treeViewProgramTree.SelectedValue));
            if (screen != null)
            {
                hiddenFieldScreenId.Value = treeViewProgramTree.SelectedValue;
                if (screen.ParentScreenId == null)
                {
                    hiddenFieldParentScreenId.Value = "0";
                }
                else
                {
                    hiddenFieldParentScreenId.Value = screen.ScreenId.ToString();
                }
                textBoxDescriptionModify.Text = screen.Description;
                textBoxProgramFileNameModify.Text = screen.ProgramFileName;
                textBoxSequenceModify.Text = screen.Sequence.ToString();
                if (String.IsNullOrEmpty(screen.ProgramFileName))
                {
                    accordionPaneAdd.Visible = true;
                    accordionInputs.SelectedIndex = 0;
                }
                else
                {
                    accordionInputs.SelectedIndex = 1;
                    accordionPaneAdd.Visible = false;
                }
            }
        }

        private void ClearInputs()
        {
            textBoxDescriptionAdd.Text = "";
            textBoxProgramFileNameAdd.Text = "";
            textBoxSequenceAdd.Text = "";
            hiddenFieldScreenId.Value = "";
            hiddenFieldParentScreenId.Value = "";
            textBoxDescriptionModify.Text = "";
            textBoxProgramFileNameModify.Text = "";
            textBoxSequenceModify.Text = "";
        }
    }
}